package it.tcm.TeacherClassMate.action;

import it.tcm.TeacherClassMate.beans.SessionUser;
import it.tcm.TeacherClassMate.beans.UserBean;
import it.tcm.TeacherClassMate.facade.UserManageBase;
import it.tcm.TeacherClassMate.form.CustomerForm;
import it.tcm.TeacherClassMate.util.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class LoggedAction extends Action {

	// --------------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Methods


	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * 
	 */

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) 
	{		
		 logger.info("LOGGED");		 
		 CustomerForm mcaForm = (CustomerForm)form;			
		 String username = "";
		 String password = "";	
		 if (mcaForm.getUsername() != null) { username = (String)mcaForm.getUsername();}
		 if (mcaForm.getPassword() != null) { password = (String)mcaForm.getPassword(); }
		 logger.info("username :" + username);
		 logger.info("password :" + password);		 
		 UserManageBase userManage = new UserManageBase();		 
		 UserBean user = userManage.getUserBeanByUsernameAndPassword(username, password);
		 if (user != null) {
			 logger.info("user is present in the database -> can LOGIN?");
			 if (user.getActivated() != null && user.getActivated().equals(1)) {
				 //metto l'utente in sessione
				 SessionUser sessionUser = new SessionUser();
				 sessionUser.setUserId(user.getId());
				 sessionUser.setFirstname(user.getName());
				 sessionUser.setLastname(user.getSurname());
				 sessionUser.setUsername(username);
				 sessionUser.setCode(user.getCode());
				 sessionUser.setAdministrator(user.getAdministrator());
				 sessionUser.setEmail(user.getEmail());
				 sessionUser.setNumVerif(user.getVerifNum());
				 request.getSession().setAttribute("sessionUser", sessionUser);
				 if(user.getAdministrator() != null && user.getAdministrator().equals(Util.ADMINISTRATOR)) {
					 return mapping.findForward("amnilogged"); 
				 } else {
					 return mapping.findForward("logged"); 
				 }
			 } else {
				 logger.info("user is NOT activated -> can NOT LOGIN");
				 return mapping.findForward("notactivated"); 
			 }
		 } else {
			 logger.info("user is NOT present in the database -> can NOT LOGIN");
			 return mapping.findForward("notlogged");
		 }
		 
		
		 
	}
	
	
}